package com.rg.demo03.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@Controller
public class FileController {
    private static final String UPLOAD_DIR = "C:/upload";
    @GetMapping("/upload")
    public String toUpload(){
        return "upload";
    }
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model) {
        model.addAttribute("uploadStatus", "上传成功！");
        for (MultipartFile file : fileUpload) {
            String fileName = file.getOriginalFilename();
            fileName = UUID.randomUUID() + "_" + fileName;
            String dirPath = "C:/upload/";
            File filePath = new File(dirPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                file.transferTo(new File(dirPath + fileName));
            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("uploadStatus", "上传失败：" + e.getMessage());
            }
        }
        return "upload";
    }
    @GetMapping("/toDownloadPage")
    public String getDownload(Model model) {
        File uploadDir = new File(UPLOAD_DIR);
        File[] files = uploadDir.listFiles();
        List<String> fileNames = new ArrayList<>();
        if (files != null) {
            for (File f : files) {
                fileNames.add(f.getName());
            }
        }
        model.addAttribute("fileNames", fileNames);
        return "download";
    }
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(@RequestParam String filename, HttpServletRequest request) throws Exception {
        // 检查 filename 是否为空
        if (filename == null || filename.isEmpty()) {
            return new ResponseEntity<>("文件名不能为空".getBytes(), org.springframework.http.HttpStatus.BAD_REQUEST);
        }
        // 指定要下载的文件路径
        String dirPath = "C:/upload/";
        // 创建文件对象
        File file = new File(dirPath + File.separator + filename);
        // 检查文件是否存在
        if (!file.exists()) {
            return new ResponseEntity<>("文件不存在".getBytes(), org.springframework.http.HttpStatus.NOT_FOUND);
        }
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        filename = getFilename(request, filename);
        // 通知浏览器以下载的形式打开
        headers.setContentDispositionFormData("attachment", filename);
        // 定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return new ResponseEntity<>(org.apache.commons.io.FileUtils.readFileToByteArray(file), headers, org.springframework.http.HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage().getBytes(), org.springframework.http.HttpStatus.EXPECTATION_FAILED);
        }
    }
    // 根据浏览器的不同进行编码设置，返回编码后的文件名
    private String getFilename(HttpServletRequest request, String filename) throws Exception {
        // 检查 filename 是否为空
        if (filename == null || filename.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                // IE内核浏览器，统一为UTF-8编码显示，并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+", " ");
            }
        }
        // 火狐等其他浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes(StandardCharsets.UTF_8), "ISO-8859-1");
    }

}